<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>首页</title>

</head>
<body>

<script>
    var ws, name, client_list={};
    function keepalive(ws) {
        var time = new Date();
        if (last_health != -1 && (time.getTime() - last_health > health_timeout)) {
            //连接断开，可设置重连或者关闭连接
            console.log('服务器没有响应')

            //ws.close();
        } else {

            console.log('连接正常')
            // if (ws.bufferedAmount == 0) {
            //     ws.send('~H#C~');
            // }
        }
    }

    function header(ws){
        ws.send({'ctl':'header','act':'check'})
        console.log('监听心跳')
    }
    // 连接服务端
    function connect(url) {
        // 创建websocket
        ws = new WebSocket(url);
        // 当socket连接打开时，输入用户名
        ws.onopen = onopen;
        // 当有消息时根据消息类型显示不同信息
        ws.onmessage = function (event) {
            onmessage(event)
        };
        ws.onclose = function() {
            console.log("连接关闭，定时重连");
            connect(url);
        };
        ws.onerror = function() {
            console.log("出现错误");
        };
    }
    // 连接建立时发送登录信息
    function onopen()
    {
        if(!name)
        {
            show_prompt();
        }
        // 登录
        var login_data = '{"ctl":"login","client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"1"}';
        console.log("websocket握手成功，发送登录数据:"+login_data);
        ws.send(login_data);
    }
    // 输入姓名
    function show_prompt(){
        name = prompt('输入你的名字：', '');
        if(!name || name=='null'){
            name = '游客';
        }
    }

    function onmessage(data){
        console.log("onmessage");
        console.log(data.data)
    }



    connect("ws://127.0.0.1:9502");

</script>
</body>
</html>